<template>
  <div class="scan-pay">
    <el-card class="pay-card">
      <div slot="header">
        <span class="card-title">微信扫码支付</span>
      </div>
      
      <el-form :model="payForm" :rules="rules" ref="payForm" label-width="100px" class="pay-form">
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="payForm.description" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        
        <el-form-item label="支付金额" prop="amount">
          <el-input-number 
            v-model="payForm.amount" 
            :precision="2" 
            :step="0.01" 
            :min="0.01"
            controls-position="right"
            placeholder="请输入金额"
            style="width: 100%;">
          </el-input-number>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="createOrder" :loading="loading">生成支付二维码</el-button>
        </el-form-item>
      </el-form>
      
      <div v-if="qrCodeUrl" class="qrcode-container">
        <div class="qrcode-wrapper">
          <qrcode-vue :value="qrCodeUrl" :size="200" level="H"></qrcode-vue>
        </div>
        <p class="qrcode-tip">请使用微信扫一扫</p>
        <p class="qrcode-order">订单号：{{ orderNo }}</p>
        <p class="qrcode-amount">金额：{{ payForm.amount }} 元</p>
        <el-button type="success" @click="checkOrderStatus">查询支付结果</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import QrcodeVue from 'qrcode.vue'
import { nativePay, generateOrderNo, yuanToFen } from '../api/pay'

export default {
  name: 'ScanPay',
  components: {
    QrcodeVue
  },
  data() {
    return {
      payForm: {
        description: '测试商品',
        amount: 0.01
      },
      rules: {
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入支付金额', trigger: 'blur' }
        ]
      },
      qrCodeUrl: '',
      orderNo: '',
      loading: false,
      // 轮询定时器ID
      pollingTimer: null,
      // 查询次数
      queryCount: 0
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    this.clearPollingTimer()
  },
  methods: {
    // 创建订单并生成二维码
    createOrder() {
      this.$refs.payForm.validate(valid => {
        if (!valid) {
          return false
        }
        
        this.loading = true
        
        // 生成订单号
        this.orderNo = generateOrderNo()
        
        // 将元转换为分
        const totalFee = yuanToFen(this.payForm.amount)
        
        // 请求扫码支付接口
        nativePay(this.orderNo, this.payForm.description, totalFee)
          .then(response => {
            this.qrCodeUrl = response.data
            this.loading = false
            
            // 开始轮询查询支付状态
            this.startPollingPayStatus()
          })
          .catch(error => {
            console.error('生成支付二维码失败', error)
            this.$message.error('生成支付二维码失败')
            this.loading = false
          })
      })
    },
    
    // 开始轮询查询支付状态
    startPollingPayStatus() {
      // 清除之前的定时器
      this.clearPollingTimer()
      
      // 重置查询次数
      this.queryCount = 0
      
      // 每隔3秒查询一次，最多查询20次（约1分钟）
      this.pollingTimer = setInterval(() => {
        this.queryCount++
        
        // 模拟查询支付结果
        if (this.queryCount >= 20) {
          this.clearPollingTimer()
          this.$message.warning('支付超时，请重新支付')
        }
        
        // 实际项目中应该调用查询订单API
        // queryOrderStatus(this.orderNo).then(...)
      }, 3000)
    },
    
    // 清除轮询定时器
    clearPollingTimer() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer)
        this.pollingTimer = null
      }
    },
    
    // 手动查询订单支付状态
    checkOrderStatus() {
      this.$message.info('查询支付结果...')
      // 实际项目中应该调用查询订单API
      // 这里只是模拟
      setTimeout(() => {
        this.$router.push({
          path: '/pay-result',
          query: {
            orderNo: this.orderNo,
            status: 'success', // 模拟支付成功，实际应该根据API返回结果
            amount: this.payForm.amount
          }
        })
      }, 1000)
    }
  }
}
</script>

<style scoped>
.scan-pay {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.pay-card {
  width: 500px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #07c160;
}

.pay-form {
  margin-top: 20px;
}

.qrcode-container {
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-wrapper {
  padding: 20px;
  background: #fff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  border-radius: 4px;
}

.qrcode-tip {
  margin-top: 15px;
  font-size: 16px;
  color: #606266;
}

.qrcode-order, .qrcode-amount {
  margin-top: 5px;
  font-size: 14px;
  color: #909399;
}

.qrcode-amount {
  margin-bottom: 15px;
}
</style> 